package org.swift.mashup.engine.util;

import org.w3c.dom.DOMException;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.Iterator;

public class XPathUtil {
	public final static String NAMESPACE = "http://www.rjlg.com/XmlMashup";
	public static final String PREFIX = "mx";
	public final static String SCHEMA_NAMESPACE = XMLConstants.W3C_XML_SCHEMA_NS_URI;
	public static final String SCHEMA_PREFIX = "xs";
	public final static String RELAX_NAMESPACE = XMLConstants.RELAXNG_NS_URI;
	public static final String RELAX_PREFIX = "ng";

	public static NamespaceContext getContext(){
		return new NamespaceContext(){
			public String getNamespaceURI(String prefix) {
				if (PREFIX.equals(prefix)){
					return NAMESPACE;
				}
				if (SCHEMA_PREFIX.equals(prefix)){
					return SCHEMA_NAMESPACE;
				}
				if (RELAX_PREFIX.equals(prefix)){
					return RELAX_NAMESPACE;
				}

				return null;
			}

			public String getPrefix(String namespaceURI) {
				return null;
			}

			@SuppressWarnings("rawtypes")
			public Iterator getPrefixes(String namespaceURI) {
				return null;
			}
		};
	}

	public static XPathExpression createXPathExpression(String xpathExpression, NamespaceContext ctx) {
		if (xpathExpression != null) {
			XPathFactory factory = XPathFactory.newInstance();
			XPath xpath = factory.newXPath();
			xpath.setNamespaceContext(ctx);
			try {
				return xpath.compile(xpathExpression);
			}
			catch (XPathExpressionException e) {
				throw new RuntimeException(e);
			}
			catch (DOMException e) {
				throw new RuntimeException(e);
			}
		}
		return null;
	}

}
